package com.example.hyznbk.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.hyznbk.MyApplication;
import com.example.hyznbk.R;
import com.example.hyznbk.model.result.DifficultReviewEntity;
import com.example.hyznbk.model.result.LearnTypeEntity;
import com.example.hyznbk.presenter.DifficultReviewPresenter;
import com.example.hyznbk.view.activity.ReviewProcessActivity;
import com.example.hyznbk.view.activity.WrongReviewActivity;
import com.example.hyznbk.view.adapter.DifficultReviewAdapter;
import com.example.hyznbk.view.adapter.PopupMenuType1Adapter;
import com.example.hyznbk.view.base.BaseMainFragment;
import com.example.hyznbk.view.base.ILoadMoreDataView;
import com.example.hyznbk.view.widget.CustomFooterView;
import com.example.hyznbk.view.widget.PopupMenu;
import com.jakewharton.rxbinding.view.RxView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.functions.Action1;


/**
 * Created by Administrator on 2017/2/6.
 */
public class DifficultReviewFragment extends BaseMainFragment<DifficultReviewPresenter> implements View.OnClickListener,ILoadMoreDataView<DifficultReviewEntity> {




    private DifficultReviewAdapter mImpAndDifTutorAdapter;

    private TextView mTvSpStatus;
    private TextView mTvSpQuesType;
    private TextView mTvTotal;
    private PopupMenuType1Adapter popupMenuStatusAdapter;
    private PopupMenu statusPopupMenu;
    private PopupMenuType1Adapter popupMenuQuesTypeAdapter;
    private PopupMenu quesTypePopupMenu;
    private View masker;
    private RelativeLayout mSpLayout;



    //private Toolbar mToolbar;

    private Map<String,Integer> quesStatusMap = new HashMap<>();
    private List<LearnTypeEntity> learnTypeList;
    private Map<String,String> LearnTypeMap = new HashMap<>();
    //private Map<String,String> quesTypeMap = new HashMap<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void updateViews(boolean isShowLoading) {
        //setHasOptionsMenu(true);
        mPresenter.getData(isShowLoading);
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_difficult_review;
    }

    @Override
    public void initBaseMainViews(View view, Bundle savedInstanceState) {
        mPresenter = new DifficultReviewPresenter(this);
        learnTypeList = ((MyApplication)getActivity().getApplication()).getLearnTypeEntities();
        RxView.clicks(mFAB)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        int[] startingLocation = new int[2];
                        mFAB.getLocationOnScreen(startingLocation);
                        startingLocation[0] += mFAB.getWidth() / 2;
                        WrongReviewActivity.launch(getHolderActivity(),1,startingLocation);
                    }
                });

        mSpLayout = (RelativeLayout) view.findViewById(R.id.rel_toolbar_head);
        mTvSpStatus = (TextView) view.findViewById(R.id.sp_status);
        mTvSpQuesType = (TextView) view.findViewById(R.id.sp_quesType);
        mTvTotal = (TextView) view.findViewById(R.id.tv_paperNumber);
        masker = view.findViewById(R.id.bg_masker);

        View toolBarLayout = view.findViewById(R.id.rel_toolbar_layout);
        ((TextView)toolBarLayout.findViewById(R.id.tv_toolbar_title)).setText(R.string.difficultReview);
        toolBarLayout.findViewById(R.id.img_main_menu).setOnClickListener(this);

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) toolBarLayout.getLayoutParams();
        layoutParams.setMargins(0,getStatusBarHeight(),0,0);
        /*mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolBar(mToolbar,false,R.string.difficultReview);*/
        //setHasOptionsMenu(true);
        mTvSpQuesType.setOnClickListener(this);

        String[] quesStatusArrays = getResources().getStringArray(R.array.QuesStatusArrays);
        String[] quesStatusName = new String[quesStatusArrays.length];
        for (int i = 0 ; i < quesStatusArrays.length ; i++){
            String[] split = quesStatusArrays[i].split("\\|");
            quesStatusName[i] = split[0];
            quesStatusMap.put(split[0], Integer.valueOf(split[1]));
        }

        popupMenuStatusAdapter = new PopupMenuType1Adapter(getHolderActivity(),quesStatusName);
        statusPopupMenu = new PopupMenu(getHolderActivity(), LinearLayout.LayoutParams.MATCH_PARENT,R.drawable.bg_popupmenu);
        statusPopupMenu.setListAdapter(popupMenuStatusAdapter);
        statusPopupMenu.setOnItemClickListener(new PopupMenu.OnItemClickListener() {
            @Override
            public void onItemClick(View item, int position, long id) {
                mTvSpStatus.setText(statusPopupMenu.getCheckedStr());
                mXRefreshView.startRefresh();
                mPresenter.getDataByStatus(quesStatusMap.get(statusPopupMenu.getCheckedStr()));
            }
        });
        mTvSpStatus.setText(statusPopupMenu.getCheckedStr());
        mTvSpStatus.setOnClickListener(this);
        statusPopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                masker.setVisibility(View.GONE);
                mTvSpStatus.setSelected(false);
            }
        });
        /*String[] quesTypeArray = new String[0];
        if(UserInfo.checkStage(UserInfo.JUNIOR_SCHOOL)){
            quesTypeArray = getResources().getStringArray(R.array.QuesType_MiddleSchool_Arrays);
        }else if(UserInfo.checkStage(UserInfo.SENIOR_SCHOOL)){
            quesTypeArray = getResources().getStringArray(R.array.QuesType_HighSchool_Arrays);
        }

        String[] quesTypeName = new String[quesTypeArray.length];
        for (int i = 0 ; i < quesTypeArray.length;i++){
            String[] split = quesTypeArray[i].split("\\|",-1);
            quesTypeName[i] = split[0];
            quesTypeMap.put(split[0],split[1]);
        }*/

        String[] learnTypeNames = new String[learnTypeList.size()];

        for (int i = 0 ; i < learnTypeList.size() ; i++){
            LearnTypeEntity learnTypeEntity = learnTypeList.get(i);
            learnTypeNames[i] = learnTypeEntity.getTypeName();
            LearnTypeMap.put(learnTypeEntity.getTypeName(),learnTypeEntity.getTypeID());
        }

        popupMenuQuesTypeAdapter = new PopupMenuType1Adapter(getHolderActivity(),learnTypeNames);
        quesTypePopupMenu = new PopupMenu(getHolderActivity(), LinearLayout.LayoutParams.MATCH_PARENT,R.drawable.bg_popupmenu);
        quesTypePopupMenu.setListAdapter(popupMenuQuesTypeAdapter);
        quesTypePopupMenu.setOnItemClickListener(new PopupMenu.OnItemClickListener() {
            @Override
            public void onItemClick(View item, int position, long id) {
                mTvSpQuesType.setText(quesTypePopupMenu.getCheckedStr());
                mXRefreshView.startRefresh();
                mPresenter.getDataByQuesType(LearnTypeMap.get(quesTypePopupMenu.getCheckedStr()));
            }
        });
        mTvSpQuesType.setText(quesTypePopupMenu.getCheckedStr());
        quesTypePopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                masker.setVisibility(View.GONE);
                mTvSpQuesType.setSelected(false);
            }
        });


        mImpAndDifTutorAdapter = new DifficultReviewAdapter(getActivity());

        mImpAndDifTutorAdapter.setCustomLoadMoreView(new CustomFooterView(getActivity()));
        mRecyclerView.setAdapter(mImpAndDifTutorAdapter);
        mImpAndDifTutorAdapter.setOnItemClickListener(new DifficultReviewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, List<DifficultReviewEntity.ImpAndDifTutorBean> list, int position) {
               mPresenter.openItemDetail(position,list.get(position));
            }
        });
    }













    @Override
    public void showNetError() {
        super.showNetError();
        setPaperTotal(0);
    }


    @Override
    public void showNoData(String msg) {
        super.showNoData(msg);
        setPaperTotal(0);
    }


    @Override
    public void loadData(DifficultReviewEntity data) {
        if(mRecyclerView.getLayoutManager() != null ) {
            mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
        }
        setPaperTotal(data.getTotalCount());
        mImpAndDifTutorAdapter.clearAndAdd(data.getModelList());
        loadComplete(mImpAndDifTutorAdapter.getAdapterItemCount() >= data.getTotalCount());
    }

    @Override
    public void loadMoreData(DifficultReviewEntity data) {
        setPaperTotal(data.getTotalCount());
        mImpAndDifTutorAdapter.add(data.getModelList());
        loadComplete(mImpAndDifTutorAdapter.getAdapterItemCount() >= data.getTotalCount());
    }



    /**
     * 没有试卷或者加载失败的逻辑处理
     */
    private void setPaperTotal(int number) {
        String paperTotal = String.format(getString(R.string.quesTotal),number);
        mTvTotal.setText(Html.fromHtml(paperTotal));
    }



  /*  @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main,menu);
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.item_other_system){
            //ToastUtils.showShort("难点进度提示");
            startActivity(new Intent(getHolderActivity(), ReviewProcessActivity.class));
            return true;
        }
        return false;
    }*/

    @Override
    public void onClick(View v) {
      switch (v.getId()){
          case R.id.sp_status:
              masker.setVisibility(View.VISIBLE);//阴影布局可见
              mTvSpStatus.setSelected(true);
              statusPopupMenu.showLocation(mSpLayout, 0, -2);
              break;
          case R.id.sp_quesType:
              masker.setVisibility(View.VISIBLE);//阴影布局可见
              mTvSpQuesType.setSelected(true);
              quesTypePopupMenu.showLocation(mSpLayout, 0, -2);
              break;
          case R.id.img_main_menu:
              startActivity(new Intent(getHolderActivity(), ReviewProcessActivity.class));
              break;
         /* case R.id.fab_coping:
              BaseReviewWrongActivity.launch(v.getContext(),1);
              break;*/
      }
    }



}